package com.wct.demo.gui;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.ExecutionException;

/**
 * @author WEI (Email:changtan20000@163.com)
 * @description
 * @date: 2019/12/22 14:31
 */
@Slf4j
@Data
public class GUIThread {
    private JTextArea textArea1;
    private JTextArea textArea2;
    private JTextArea textArea3;
    private JTextArea textArea4;
    private JLabel topLabel;
    private JLabel label1;
    private JLabel label2;
    private JLabel label3;
    private JLabel label4;
    private JPanel mainPanel;

    public JPanel getMainPanel() {
        return mainPanel;
    }

    public void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setContentPane(new GUIThread().getMainPanel());

        frame.setSize(900, 600);
        // 设置窗体居中显示
        frame.setLocationRelativeTo(null);
        // 设置当窗体关闭的操作时，程序结束
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        // 设置窗体可显示
        frame.setVisible(true);

    }

    public synchronized void update(final String value) {
        SwingWorker worker = new SwingWorker<String, Void>() {
            @Override
            protected String doInBackground() {
                return value;
            }

            @Override
            protected void done() {
                try {
                    topLabel.setText(get());
                    label1.setText(get());
                    label2.setText(get());
                    label3.setText(get());
                    label4.setText(get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
                log.debug("threadId: {}, text: {}", Thread.currentThread().getId(), topLabel.getText());
            }
        };
        worker.execute();
    }

    /*
     * rows 行数
     * cols 列数
     */
    public static void main(String[] args) throws Exception {
        GUIThread guiThread = new GUIThread();

        SwingUtilities.invokeLater(() -> {
            guiThread.createAndShowGUI();
        });

        Thread.sleep(3000);

        guiThread.update("123456");

        Thread.sleep(3000);
        log.debug("threadId: {}", Thread.currentThread().getId());
    }

}
